package com.sy.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import com.sy.model.DocAffix;
import com.sy.dao.AffixDao;
import com.sy.service.AffixService;

@SuppressWarnings("unused")
public class AffixServiceImp implements AffixService {
	private AffixDao affixDao;
	private static String affixDir = "/AffixDir";
	private static final int BUFFER_SIZE = 16 * 1024;
	
	/**
	 * 通过id删除
	 */
	public void deleteByAffixId(Long docAffixId) {
		DocAffix docAffix=affixDao.queryById(docAffixId);
		File file=new File(ServletActionContext.getServletContext().getRealPath("") + "/" + docAffix.getDocAffixPath());
		file.delete();
		affixDao.del(docAffix);
	}
	
	/**把附件上传到webapps*/
	private String uploadAffix(File file, String fileName) throws Exception {
        String name = null;
        int pos = fileName.lastIndexOf(".");
        if (pos != -1) {
            name = fileName.substring(pos);
        } else {
            name = fileName;
        }
        // 附件名唯一性：时间戳+UUID
        UUID uid = UUID.randomUUID();
        String imageFileName = new Date().getTime() + uid.toString() + name;
        File imageFile = new File(ServletActionContext.getServletContext().getRealPath(affixDir) + "/" + imageFileName);
        File path = new File(ServletActionContext.getServletContext().getRealPath(affixDir));
        if (!path.exists()) {
            path.mkdir();
        }
        InputStream in = null;
        OutputStream out = null;
        try {
        	in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(imageFile),
					BUFFER_SIZE);			
			int canRead = in.available();
			for(int i=0;i<=canRead /BUFFER_SIZE;i++){
				byte[] buffer = new byte[BUFFER_SIZE];
				if((canRead-i*BUFFER_SIZE)/BUFFER_SIZE==0){
					buffer = new  byte[canRead-i*BUFFER_SIZE];					
				}
				in.read(buffer);
				out.write(buffer);
			}
        } finally {
            if (null != in) {
                in.close();
            }
            if (null != out) {
                out.close();
            }
        }
        return affixDir + "/" + imageFileName;
    }
	
    /**
     * 得到附件的大小
     * @param f
     * @return
     */
    private String getAffixSize(File f) {
        DecimalFormat df = new DecimalFormat("#.##");
        long size = f.length();
        BigDecimal b1 = new BigDecimal(size);
        BigDecimal b2 = new BigDecimal(1024);
        MathContext m = new MathContext(3);
        String affixSize = df.format(b1.divide(b2, m)) + "KB";
        return affixSize;
    }

    /**
     * 保存数据库
     */
	public String uploadFile(String classType, String uuid, String projectId,
			String[] fileParameter) {
		StringBuffer sb=new StringBuffer();
		DocAffix docAffix=new DocAffix();
		docAffix.setDocAffixSort(classType);
		docAffix.setDocAffixCreate(new Date());
		docAffix.setDocAffixName(fileParameter[0]);
		if(projectId!=null&&!projectId.equals("")){
			docAffix.setProjectId(projectId);
		}else{
			docAffix.setProjectId(uuid.toString());
		}
		docAffix.setDocAffixType(fileParameter[2]);
		docAffix.setAffixSize(fileParameter[1]);
		docAffix.setDocAffixPath(fileParameter[3]);
		affixDao.save(docAffix);
		sb.append(docAffix.getDocAffixName()+","+docAffix.getDocAffixId());
		return sb.toString();
	}

	public DocAffix getAffixWithContentById(Long docAffixId) {
		return affixDao.queryById(docAffixId);
	}

	public AffixDao getAffixDao() {
		return affixDao;
	}

	public void setAffixDao(AffixDao affixDao) {
		this.affixDao = affixDao;
	}
}
